﻿using System;
using System.Diagnostics;
using System.Text;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

using Newtonsoft.Json;
using ZLWeb.WebApiConfigration.WebapiAppsetting;

namespace ZLWeb.WebApiInfrastructure.Filter
{
    /// <summary>
    ///     运行日志
    ///     全局设置开关跟踪级别 0 不跟踪
    ///     1-基本跟踪（请求只跟踪url，不序列化参数，返回只跟踪执行时间，HTTP状态码）
    ///     2-完全跟踪（请求跟踪url，序列化参数，返回跟踪执行时间，HTTP状态码，返回的HTTPContent）
    ///     方法上有 noRunlog特性的无视上述配置，都不跟踪
    ///     todo 策略考虑使用策略模式重构
    /// </summary>
    public class RunLogAtrribute : ActionFilterAttribute
    {
        private readonly string _httpGuid = Guid.NewGuid().ToString();
        private Stopwatch _stopwatch = new Stopwatch();

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            //当全局配置不记日志，返回
            if (ZLWebApiAppSetting.GetAppSetting().RunLogLevel == "0") return;
            //当当前ACTION有NoRunLogAttribute标签返回
            if (actionContext.ActionDescriptor.GetCustomAttributes<NoRunLogAttribute>().Count > 0) return;
            _stopwatch = Stopwatch.StartNew();
            //地址
            var builder = new StringBuilder();
            builder.AppendLine("本次请求随机号：" + _httpGuid);
            builder.AppendLine("请求Http(" + actionContext.Request.Method + ")上下文：");
            builder.AppendLine(actionContext.Request.RequestUri.ToString());
            builder.AppendLine(actionContext.Request.Headers.ToString());

            if (ZLWebApiAppSetting.GetAppSetting().RunLogLevel == "2")
            {
                builder.AppendLine("请求参数：");
                foreach (var info in  actionContext.ActionArguments)
                {
                    var josn = string.Empty;


                    josn = JsonConvert.SerializeObject(info.Value);

                    builder.AppendLine(info.Key + "：" + josn);
                }
            }
       
            base.OnActionExecuting(actionContext);
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            //当全局配置不记日志，返回
            if (ZLWebApiAppSetting.GetAppSetting().RunLogLevel == "0") return;
            //当当前ACTION有NoRunLogAttribute标签返回
            if (actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes<NoRunLogAttribute>().Count > 0)
                return;
            _stopwatch.Stop();
            var builder = new StringBuilder();
            builder.AppendLine("本次请求随机号：" + _httpGuid);
            builder.AppendLine("本次请求耗时：" + _stopwatch.ElapsedMilliseconds + "ms");
            if (actionExecutedContext.Exception != null)
                builder.AppendLine("错误：" + actionExecutedContext.Exception.Message);
            if (actionExecutedContext.Response != null)
                builder.AppendLine("本次请求返回HTTP状态码：" + actionExecutedContext.Response.StatusCode);
            if (ZLWebApiAppSetting.GetAppSetting().RunLogLevel == "2")
            {
                if (actionExecutedContext.Response != null)
                {
                    builder.AppendLine("返回结果：");
                    builder.AppendLine(actionExecutedContext.Response.Content.ReadAsStringAsync().Result);
                }
            }
            base.OnActionExecuted(actionExecutedContext);
        }
    }
}